/***************************************************************************
 *
 *  Rain
 *    PHP Object Oriented Framework
 *
 *  Copyright (C) 2006  Oto Komiňák  <oto@kominak.sk>
 *
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 *
 **************************************************************************/


// localization

var locale = new Array();

locale["en"] = new Array();
locale["sk"] = new Array();

locale["en"]["required"] = "Required";
locale["sk"]["required"] = "Povinné";

locale["en"]["ok"] = "OK";
locale["sk"]["ok"] = "OK";

locale["en"]["optional"] = "Optional";
locale["sk"]["optional"] = "Nepovinné";

locale["en"]["max_length"] = "Max.length";
locale["sk"]["max_length"] = "Max.dĺžka";

locale["en"]["min_length"] = "Min.length";
locale["sk"]["min_length"] = "Min.dĺžka";

locale["en"]["wrong_email"] = "Wrong email";
locale["sk"]["wrong_email"] = "Nesprávny email";

locale["en"]["strange_email"] = "Strange email";
locale["sk"]["strange_email"] = "Zvláštny email";

locale["en"]["format"] = "Format";
locale["sk"]["format"] = "Formát";

locale["en"]["dd_mm_yyyy"] = "DD.MM.YYYY";
locale["sk"]["dd_mm_yyyy"] = "DD.MM.RRRR";

locale["en"]["wrong_phone"] = "Wrong phone no.";
locale["sk"]["wrong_phone"] = "Nesprávne tel.č.";

locale["en"]["wrong_number"] = "Wrong number";
locale["sk"]["wrong_number"] = "Nesprávne číslo";

locale["en"]["minimum"] = "Minimum";
locale["sk"]["minimum"] = "Minimum";

locale["en"]["maximum"] = "Maximum";
locale["sk"]["maximum"] = "Maximum";

/*
locale["en"][""] = "";
locale["sk"][""] = "";

locale["en"][""] = "";
locale["sk"][""] = "";

locale["en"][""] = "";
locale["sk"][""] = "";
*/



var nbsp = 160;    // non-breaking space char
var node_text = 3; // DOM text node-type
var emptyString = /^\s*$/
var glb_vfld;      // retain vfld for timer thread



// Trim leading/trailing whitespace off string

function trim(str) {
    return str.replace(/^\s+|\s+$/g, '');
}


// Delayed focus setting to get around IE bug

function setFocusDelayed() {
    glb_vfld.focus();
}


function setfocus(vfld) {
    glb_vfld = vfld;
    setTimeout('setFocusDelayed()', 100);
}


// Display warn/error message in HTML element
// commonCheck routine must have previously been called

function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
    // setting an empty string can give problems if later set to a 
    // non-empty string, so ensure a space present. (For Mozilla and Opera one could 
    // simply use a space, but IE demands something more, like a non-breaking space.)
    var dispmessage;
    if (emptyString.test(message)) 
        dispmessage = String.fromCharCode(nbsp);        
    else    
        dispmessage = message;

    var elem = document.getElementById(fld);
    elem.firstChild.nodeValue = dispmessage;    
    
    elem.className = msgtype;     // set the CSS class to adjust appearance of message
}


// Common code for all validation routines to:
// (a) check for older / less-equipped browsers
// (b) check if empty fields are required
// Returns true (validation passed), 
//         false (validation failed) or 
//         proceed (don't know yet)

var proceed = 2;  

function commonCheck(vfld,   // element to be validated
                     ifld,   // id of element to receive info/error msg
                     reqd)   // true if required
{
    if (!document.getElementById) 
        return true;    // not available on this browser - leave validation to the server
    var elem = document.getElementById(ifld);
    if (!elem.firstChild)
        return true;    // not available on this browser 
    if (elem.firstChild.nodeType != node_text)
        return true;    // ifld is wrong type of node    

    if (emptyString.test(vfld.value)) {
        if (reqd) {
            msg(ifld, "error", locale[lang]["required"]);    
            setfocus(vfld);
            return false;
        }
        else {
            if (reqd) msg(ifld, "info", locale[lang]["ok"]);     // OK
            else msg(ifld, "info-nreq", locale[lang]["optional"]);     // OK
                
            return true;    
        }
    }
    return proceed;
}


// Validate if something has been entered
// Returns true if so 

function validatePresent(vfld,   // element to be validated
                         ifld)   // id of element to receive info/error msg
{       
    var stat = commonCheck(vfld, ifld, true);
    if (stat != proceed) return stat;

    msg(ifld, "info", locale[lang]["ok"]);
    return true;
}


function validateStr(vfld, ifld, reqd, min, max) {
  var stat = commonCheck(vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var errlevel = "error";
  if (!reqd) errlevel = "warn";
  
  if (tfld.length < min) {
      msg(ifld, errlevel, locale[lang]["min_length"] + ": " + min);
      setfocus(vfld);
      return false;
  } else if (tfld.length > max) {
      msg(ifld, errlevel, locale[lang]["max_length"] + ": " + max);
      setfocus(vfld);
      return false;
  }

  msg(ifld, "info", locale[lang]["ok"]);

  return true;
}


function validateStr2(vfld, ifld, reqd, min, max) {
  var stat = commonCheck(vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var errlevel = "error";
  if (!reqd) errlevel = "warn";

} 



// Validate if e-mail address
// Returns true if so (and also if could not be executed because of old browser)

function validateEmail(vfld,   // element to be validated
                       ifld,   // id of element to receive info/error msg
                       reqd)   // true if required
{
  var stat = commonCheck(vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
  if (!email.test(tfld)) {
    msg(ifld, "error", locale[lang]["wrong_email"]);
    setfocus(vfld);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/
  if (!email2.test(tfld)) 
    msg(ifld, "warn", locale[lang]["strange_email"]);
  else {
      msg(ifld, "info", locale[lang]["ok"]);
  }
  return true;
}


function validateDate(vfld,   // element to be validated
                      ifld,   // id of element to receive info/error msg
                      reqd)   // true if required
{
  var stat = commonCheck(vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var format = /^[0-3][0-9]\.[0-1][0-9]\.[1-2][0-9]{3}$/
  if (!format.test(tfld)) {
    msg(ifld, "error", locale[lang]["format"] + ": " + locale[lang]["dd_mm_yyyy"]);
    setfocus(vfld);
    return false;
  }
  else
    msg (ifld, "info", locale[lang]["ok"]);

  return true;
}


function validateICO(vfld,   // element to be validated
                     ifld,   // id of element to receive info/error msg
                     reqd)   // true if required
{
  // nn nnn nnn, nnnnnnnn

  var stat = commonCheck(vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var format = /^[0-9]{2} ?[0-9]{3} ?[0-9]{3}$/
  if (!format.test(tfld)) {
    msg(ifld, "error", "Nesprávne IČO");
    setfocus(vfld);
    return false;
  }
  else
    msg (ifld, "info", "OK");

  return true;
}


function validateDIC(vfld,   // element to be validated
                     ifld,   // id of element to receive info/error msg
                     reqd)   // true if required
{
  var stat = commonCheck(vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var format = /^[0-9]{3} ?[0-9]{3} ?[0-9]{4}\/?[0-9]{0,4}$/
  if (!format.test(tfld)) {
    msg(ifld, "error", "Nesprávne DIČ");
//    setfocus(vfld);
    return false;
  }
  else
    msg (ifld, "info", "OK");

  return true;
}


function validateZIP(vfld,   // element to be validated
                     ifld,   // id of element to receive info/error msg
                     reqd)   // true if required
{
  // nnn nn, nnnnn

  var stat = commonCheck(vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var zip = /^[0-9]{3} ?[0-9]{2}$/
  if (!zip.test(tfld)) {
    msg(ifld, "error", "Nesprávne PSČ");
    setfocus(vfld);
    return false;
  }
  else
    msg (ifld, "info", "OK");

  return true;
}


// Validate telephone number
// Returns true if so (and also if could not be executed because of old browser)
// Permits spaces, hyphens, brackets and leading +

function validatePhone(vfld,   // element to be validated
                       ifld,   // id of element to receive info/error msg
                       reqd)   // true if required
{
  var stat = commonCheck(vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var telnr = /^\+?[0-9 ()-]+[0-9]$/
  if (!telnr.test(tfld)) {
    msg(ifld, "error", locale[lang]["wrong_phone"]);
    setfocus(vfld);
    return false;
  }

  var numdigits = 0;
  for (var j=0; j<tfld.length; j++)
    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;

  if (numdigits<6) {
    msg(ifld, "error", locale[lang]["wrong_phone"]);
    setfocus(vfld);
    return false;
  }


//  if (numdigits>14)
//    msg (ifld, "warn", numdigits + " digits - check if correct");
//  else { 
//    if (numdigits<10)
//      msg (ifld, "warn", "Only " + numdigits + " digits - check if correct");
    else
      msg (ifld, "info", locale[lang]["ok"]);
//  }

  return true;
};



// Validate person's age
// Returns true if OK 

function validateAge(vfld,   // element to be validated
                     ifld,   // id of element to receive info/error msg
                     reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);
  var ageRE = /^[0-9]{1,3}$/
  if (!ageRE.test(tfld)) {
    msg(ifld, "error", "ERROR: not a valid age");
    setfocus(vfld);
    return false;
  }

  if (tfld>=200) {
    msg (ifld, "error", "ERROR: not a valid age");
    setfocus(vfld);
    return false;
  }

  if (tfld>110) msg(ifld, "warn", "Older than 110: check correct");
  else {
    if (tfld<7) msg(ifld, "warn", "Bit young for this, aren't you?");
    else        msg(ifld, "warn", "");
  }
  return true;
}


function validateInt(vfld,   // element to be validated
                     ifld,   // id of element to receive info/error msg
                     reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);
  var ageRE = /^[0-9]+$/
  if (!ageRE.test(tfld)) {
    msg(ifld, "error", locale[lang]["wrong_number"]);
    setfocus(vfld);
    return false;
  }

  msg (ifld, "info", locale[lang]["ok"]);
  return true;
}


function validateInt2(vfld,   // element to be validated
                     ifld,   // id of element to receive info/error msg
                     reqd,   // true if required
                     min, max)
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);
  var ageRE = /^[0-9]+$/
  if (!ageRE.test(tfld)) {
    msg(ifld, "error", locale[lang]["wrong_number"]);
    setfocus(vfld);
    return false;
  }

  if ((max != "x") && (tfld > max)) {
    msg (ifld, "error", locale[lang]["maximum"] + ": " + max);
    setfocus(vfld);
    return false;
  }

  if ((min != "x") && (tfld < min)) {
    msg (ifld, "error", locale[lang]["minimum"] + ": " + min);
    setfocus(vfld);
    return false;
  }

  msg (ifld, "info", "OK");
  return true;
}


function validateFloat(vfld,   // element to be validated
                       ifld,   // id of element to receive info/error msg
                       reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);
  var floatRE = /^[0-9]*[,.]?[0-9]+$/
  if (!floatRE.test(tfld)) {
    msg(ifld, "error", "Neplatné desatinné číslo");
    setfocus(vfld);
    return false;
  }

  msg (ifld, "info", "OK");
  return true;
}


function directValidateInt2(vfld,   // element to be validated
                            min, max)
{
  var tfld = trim(vfld.value);
  var ageRE = /^[0-9]+$/
  if (!ageRE.test(tfld)) {
    alert("Neplatné číslo!");
    setfocus(vfld);
    return false;
  }

  if ((max != "x") && (tfld > max)) {
    alert("Maximum: " + max);
    setfocus(vfld);
    return false;
  }

  if ((min != "x") && (tfld < min)) {
    alert("Minimum: " + min);
    setfocus(vfld);
    return false;
  }

  return true;
}


function openWin(img) {
    window.open(img, 'w', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width=660,height=660');
}


function openWinWH(img, w, h) {
    window.open(img, 'w', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width='+w+',height='+h);
}


function openWinWHScroll(img, w, h) {
    window.open(img, 'w', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width='+w+',height='+h);
}


function toggleVisibility(d) {
    elem = document.getElementById(d);
    if (elem.style.visibility == 'hidden') elem.style.visibility = 'visible';
    else elem.style.visibility = 'hidden';
}


function setVisibility(d, vis) {
    elem = document.getElementById(d);
    if (vis) elem.style.visibility = 'visible';
    else     elem.style.visibility = 'hidden';
}

